package com.oceansoft.mobile.econsole.modules.api.v2.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.encrypt.DesAPPUtils;
import com.oceansoft.mobile.econsole.modules.api.service.IMattersService;
import com.oceansoft.mobile.econsole.modules.api.v2.service.ICaseService;
import com.oceansoft.mobile.econsole.modules.api.v2.service.IProjectYyService;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.jlwt.entity.CaseBasis;
import com.oceansoft.mobile.econsole.modules.jlwt.entity.CaseMeterial;
import com.oceansoft.mobile.econsole.modules.jlwt.entity.SysOrg;
import com.oceansoft.mobile.econsole.modules.matters.entity.CaseInfo;
import com.oceansoft.mobile.econsole.modules.matters.entity.CaseJgEnt;
import com.oceansoft.mobile.econsole.modules.matters.entity.CaseListEnt;
import com.oceansoft.mobile.econsole.modules.matters.entity.CaseQuery;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory;
import com.oceansoft.mobile.econsole.modules.weixin.entity.*;
import com.oceansoft.mobile.econsole.modules.weixin.service.WeixinQueryService;
import com.oceansoft.mobile.econsole.weixin.api.OauthAPI;
import com.oceansoft.mobile.econsole.weixin.api.enums.OauthScope;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Class: ApiCaseController
 * Title: 事项中心
 * Desc: 市民通过辖区、警种、分类、筛选、查询事项
 * <p>
 * Created： wzy
 * Date： 2016/1/31
 */
@Controller
@RequestMapping("api/case")
public class ApiCaseController extends BaseController {

    @Resource
    private ICaseService caseService;

    @Resource
    private IMattersService mattersService;

    @Resource
    private IMemberService memberService;

    @Resource
    private IWtMemberService wtMemberService;

    @Resource
    IProjectYyService projectYyService;

    @Resource
    private WeixinQueryService weixinQueryService;

    /**
     * 进入办事中心oauth认证
     */
    @RequestMapping(value = "baseOauth", method = GET)
    public String gotoCaseCenterOAuth(HttpServletRequest request) {
        OauthAPI oauthAPI = WxFactory.buildOauthAPI();
        return "redirect:" + oauthAPI.getOauthPageUrl(WxFactory.CASECENTER_OAUTH_URL, OauthScope.SNSAPI_BASE, "123");
    }

    @RequestMapping(value = "showCase",method = GET)
    public String gotoCaseShow(){
        return "weixin/item/case_show";
    }

    @RequestMapping(value = "show_report",method = GET)
    public String gotoReportShow(Model model)
    {
        if (null == getWxMemberSession()) {
            OauthAPI oauthAPI = WxFactory.buildOauthAPI();
            return "redirect:" + oauthAPI.getOauthPageUrl(WxFactory.PERCENTER_OAUTH_URL, OauthScope.SNSAPI_BASE, "123");
        }else
        if("1".equals(getWxMemberSession().getIdentifystatus())){
            model.addAttribute("aliasNameWjb", getWxMemberSession().getAliasName());
            model.addAttribute("telephoneWjb", getWxMemberSession().getMobile());
        }
        return "weixin/item/case_report";
    }

    @RequestMapping(value = "show_reserve",method = GET)
    public String gotoReserveShow(Model model){
        if (null == getWxMemberSession()) {
            OauthAPI oauthAPI = WxFactory.buildOauthAPI();
            return "redirect:" + oauthAPI.getOauthPageUrl(WxFactory.PERCENTER_OAUTH_URL, OauthScope.SNSAPI_BASE, "123");
        }else
        if("1".equals(getWxMemberSession().getIdentifystatus())){
            model.addAttribute("aliasNameWjb", getWxMemberSession().getAliasName());
            model.addAttribute("telephoneWjb", getWxMemberSession().getMobile());
        }
        return "weixin/item/case_reserve";
    }
    /**
     * 事项列表查询
     *
     * @param
     * @return 事项列表
     */
    @ResponseBody
    @RequestMapping(value = "caselist", method = POST)
    public Result getCaseList(HttpServletRequest request) {

        String kw=request.getParameter("keywords");
        String jz=request.getParameter("jz");
        String pageNum=request.getParameter("pageNum");
        String caseType=request.getParameter("caseType");
        String url=configInfo.getServiceInterfaceAddress()+"/matters/page?ps=10";
        if(StringUtils.isNotEmpty(caseType)) {
           url+="&caseType="+caseType;
        }
        if(StringUtils.isNotEmpty(kw)){
            url+="&kw="+kw;
        }
        if(StringUtils.isNotEmpty(pageNum)){
            url+="&pi="+pageNum;
        }else{
            url+="&pi=1";
        }
        url+="&pcc="+jz;
            String res="";
        try {
            res = HttpClientUtil.doGet(url);
//            res = HttpClientUtil.doGet("http://172.17.100.132:9008/matters/page?kw="+kw+"&pi="+pageNum+"&ps=10&ppc="+jz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject object = JSON.parseObject(res);
        JSONObject json=(JSONObject)object.get("data");
        System.out.println(json.toString());
//        Pager<CaseListEnt> result = caseService.getCaseList(query);
        if (json.size()>0) {
            return new Result(Result.SUCC, json);
        }
        return new Result(Result.FAILURE, "暂无数据!");


    }

    /**
     * 进入办事大厅首页
     * @param request
     * @param query
     * @param model
     * @return
     */
    @RequestMapping(value = "caseCenter" ,method = GET)
    public String gotoCaseIndex(HttpServletRequest request, CaseQuery query, Model model) {
        try{
           Result r= mattersService.loadAllPoliceCatalog();
            model.addAttribute("jz",r.getData());

            model.addAttribute("query",query);
        }catch (Exception e){e.printStackTrace();}
        return "weixin/item/case_center";
    }


    @ResponseBody
    @RequestMapping(value = "jgCaseList", method = GET)
    public Result getJgCaseList() {
        List<CaseJgEnt> result = caseService.getJgCaseList();
        return new Result(Result.SUCC, result);
    }

    @ResponseBody
    @RequestMapping(value = "confirm/{userGuid}", method = GET)
    public Result IsConfirm(@PathVariable("userGuid") String userGuid) {
        String s = memberService.isConfirm(userGuid);
        return new Result(Result.SUCC, s, "认证成功");

    }


    @ResponseBody
    @RequestMapping(value = "jgCaseOrg/{orgid}/{caseno}", method = GET)
    public Result getJgCaseOrg(@PathVariable("orgid") String OrgId, @PathVariable("caseno") String caseno) {
        List<SysOrg> result = caseService.getJgCaseOrg(OrgId, caseno);
        return new Result(Result.SUCC, result);
    }

    @RequestMapping(value = "index")
    public String gotoCaseIndex(CaseQuery query, Model model, HttpServletRequest request) throws Exception {
        WxMember wxMember = getWxMember(request);//微信用户
        String openId = wxMember.getOpenId();
        model.addAttribute("openId",openId);
        WtMember wtMember = wtMemberService.getWtMemberByOpenid(openId);//用户表数据
        String keyword = request.getParameter("keyword") == null ? "" : request.getParameter("keyword").toString();
//            String openid = request.getParameter("openid") == null ? "" : request.getParameter("openid").toString();
        query.setNumPerPage(10);
        query.setOrgId("230600000000");
        Pager<CaseListEnt> result = caseService.getCaseList(query);
        if(Objects.isNull(wtMember)) {
            model.addAttribute("userGuid", "");
        }  else {
            model.addAttribute("userGuid", wtMember.getGuid());
        }
//        model.addAttribute("userGuid", "dbe51d34-47dd-4a12-82d5-3959a3fd1ffd");
        model.addAttribute("pager", result);
        model.addAttribute("keyword", keyword);
        return "weixin/item/item_center";
    }

    /**
     * 根据标准事项返回市局
     *
     * @param caseguid 标准事项Guid
     * @return 存在标准事项的市区，包括子组织结构
     */
    @ResponseBody
    @RequestMapping(value = "casesregion/{caseguid}", method = GET)
    public Result getCaseRegion(@PathVariable("caseguid") String caseguid) {

        List<SysOrg> orgs = caseService.getCaseRegion(caseguid);
        for (SysOrg e : orgs) {
            e.setOrgName(e.getOrgName().replace("公安局", ""));

        }
        if (!orgs.isEmpty()) {
            return new Result(Result.SUCC, orgs);
        }
        return new Result(Result.FAILURE, "暂无数据");

    }

    /**
     * 根据标准事项Guid，父组织结构获取分局
     *
     * @param caseguid    标准事项Guid
     * @param parentorgid 父组织结构ID
     * @return 存在标准事项的分局，包括之组织结构
     */
    @ResponseBody
    @RequestMapping(value = "casesubstaion/{caseguid}/{parentorgid}", method = GET)
    public Result getCaseSubStation(@PathVariable("caseguid") String caseguid, @PathVariable("parentorgid") String parentorgid) {

        List<SysOrg> orgs = caseService.getCaseStation(caseguid, parentorgid);

        if (orgs != null) {
            return new Result(Result.SUCC, orgs);
        }
        return new Result(Result.FAILURE, "暂无数据");

    }

    /**
     * 根据标准事项Guid，获取派出所，大队，等组织结构
     *
     * @param caseguid    事项标准Guid
     * @param parentorgid 父组织结构Guid
     * @return 返回组织结构
     */
    @ResponseBody
    @RequestMapping(value = "casepcs/{caseguid}/{parentorgid}", method = GET)
    public Result getCasePcs(@PathVariable("caseguid") String caseguid, @PathVariable("parentorgid") String parentorgid) {

        List<SysOrg> orgs = caseService.getCasePcs(caseguid, parentorgid);

        if (orgs != null) {
            return new Result(Result.SUCC, orgs);
        }
        return new Result(Result.FAILURE, "暂无数据");

    }

    /**
     * 根据标准事项Guid,部门id返回 事项指南信息
     *
     * @param orgid 部门Guid
     * @return 事项信息
     */
    @ResponseBody
    @RequestMapping(value = "caseinfo/{caseNo}/{orgid}", method = GET)
    public Result getCaseInfo(@PathVariable("caseNo") String caseNo, @PathVariable("orgid") String orgid) {

        CaseInfo caseInfo = caseService.getCaseInfo(caseNo, orgid);

        if (caseInfo != null) {
            return new Result(Result.SUCC, caseInfo);
        }

        return new Result(Result.FAILURE, "暂无数据");

    }

    /**
     * 根据标准事项Guid,部门id返回 事项指南信息
     *
     * @param model
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "detail", method = GET)
    public String caseDetail(@RequestParam("caseNo") String caseNo, Model model, HttpServletRequest request) {
        String guid =request.getParameter("guid");
        if(Strings.isNullOrEmpty(guid)){
            model.addAttribute("guid","0");
        }else{
            model.addAttribute("guid",guid);
        }
        try {
            caseService.doCaseInfo(model,caseNo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("caseNo", caseNo);
        return "weixin/item/case_detail";
    }

    @RequestMapping(value = "order", method = POST)
    public String caseDetail(HttpServletRequest request, Model model) throws IOException {

        String pt = request.getParameter("pt");
        String userGuid = request.getParameter("userGuid");
        if (StringUtils.isNotBlank(userGuid)) {
            WtMember wtMember = wtMemberService.getWtMemberByUserGuid(userGuid);
//            String idCard = "";
            if (StringUtils.isNotBlank(wtMember.getUserCode())) {
                try {
                    // 解密身份证号
                    String userCode = DesAPPUtils.decrypt(wtMember.getUserCode());
//                    idCard = userCode.substring(0, 6) + "***********" + userCode.substring(17);
                    wtMember.setUserCode(userCode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            model.addAttribute("member", wtMember);
        }

        String caseNo = request.getParameter("caseNo");
        String orgid = request.getParameter("orgid");
        CaseInfo caseInfo = caseService.getCaseInfo(caseNo, orgid);
        // 获取事项材料列表
        String url = Constant.ProjectUploadIP + "/WebApi/Product/GetCaseMaterial?refID=" + caseInfo.getRefGuid();
        //String url = "http://gafw.jl.gov.cn/WebApi/Product/GetCaseMaterial?refID="+caseInfo.getRefGuid();
        // 事项列表json
        String sxlb = "";
        try {
            sxlb = HttpClientUtil.doGet(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject sxlbJsonObject = JSON.parseObject(sxlb);
        ArrayList list = new ArrayList();
        JSONArray jsonArray = (JSONArray)sxlbJsonObject.get("data");
        StringBuffer ismust = new StringBuffer("");
        for(int i = 0; i < jsonArray.size(); i++){
            HashMap<String,String> hm = new HashMap<String,String>();
            JSONObject sxJsonObject = JSON.parseObject(jsonArray.get(i).toString());
            hm.put("guid",sxJsonObject.get("GUID")+"");
            hm.put("fileguid",sxJsonObject.get("FILEGUID")+"");
            hm.put("material",sxJsonObject.get("MATERIAL")+"");
            hm.put("ismust",sxJsonObject.get("ISMUST")+"");
            hm.put("stype",sxJsonObject.get("STYPE")+"");
            hm.put("materialtypes",sxJsonObject.get("MATERIALTYPES")+"");
            hm.put("rownum",sxJsonObject.get("ROWNUM")+"");
            list.add(hm);
            if("1".equals(sxJsonObject.get("ISMUST").toString())){
                ismust.append(i).append(",");
            }
        }
        if(ismust.length()>0){
            ismust.deleteCharAt(ismust.length()-1);
        }
        model.addAttribute("ismust",ismust);
        model.addAttribute("sxlb",list);
        model.addAttribute("caseInfo", caseInfo);

        model.addAttribute("caseNo", caseNo);
        model.addAttribute("orgid", orgid);
        model.addAttribute("userGuid", userGuid);
        model.addAttribute("pt", pt);
        // 预约日期
        List<String> yyrq = projectYyService.getYyDataArrange("7");
        model.addAttribute("yyrq", yyrq);
        return "weixin/bmsrv/item_order";
    }

    /**
     * 跳转到事项申报页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "goToApply",method = POST)
    public String goToApply(Model model, HttpServletRequest request) throws Exception {
        String caseNo = request.getParameter("caseNo");
        String orgid = request.getParameter("orgid");
        String userGuid = request.getParameter("userGuid");
//        String expertneturl = request.getParameter("expertneturl");
        String pt = request.getParameter("pt");

        CaseInfo caseInfo = caseService.getCaseInfo(caseNo, orgid);
        if (caseInfo != null) {
            model.addAttribute("caseInfo", caseInfo);

            Result result = mattersService.loadApplyMataer(caseInfo.getRefGuid(), null);
            if (result.isSucc()) {
                List<CaseMeterial> list = (List<CaseMeterial>) result.getData();
                if (!list.isEmpty()) {
                    model.addAttribute("caseMeterialList", list);
                }
            }

            Result basisResult = mattersService.loadCaseBasis(caseInfo.getGuid());
            if (basisResult.isSucc()) {
                List<CaseBasis> basisList = (List<CaseBasis>) basisResult.getData();
                if (basisList != null) {
                    model.addAttribute("caseBasisList", basisList);
                }
            }
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(userGuid)) {
            WtMember wtMember = wtMemberService.getWtMemberByUserGuid(userGuid);
            wtMember.setUserCode(DesAPPUtils.decrypt(wtMember.getUserCode()));
            wtMember.setMobile(DesAPPUtils.decrypt(wtMember.getMobile()));
            model.addAttribute("wtMember", wtMember);

            if (wtMember == null) {
                model.addAttribute("yyflag", "false");
            } else {
                if ("0".equals(wtMember.getUserType()) && "1".equals(caseInfo.getCaseKindType())) {
                    model.addAttribute("yyflag", "true");
                } else if ("1".equals(wtMember.getUserType()) && "2".equals(caseInfo.getCaseKindType())) {
                    model.addAttribute("yyflag", "true");
                } else {
                    model.addAttribute("yyflag", "false");
                }
            }
        } else {
            model.addAttribute("yyflag", "false");
        }

        model.addAttribute("caseNo", caseNo);
        model.addAttribute("orgid", orgid);
        model.addAttribute("userGuid", userGuid);
//        model.addAttribute("expertneturl", expertneturl);
        model.addAttribute("pt", pt);
        // 实名认证
        if (!"(null)".equals(userGuid)) {
            String rzResult = memberService.rz(userGuid);
            model.addAttribute("rzResult", rzResult);
        }

        return "weixin/bmsrv/item_apply";
    }


    /**
     * 事项申报
     * @param baseSb
     * @param map
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "projectApply", method = POST)
    public boolean projectApply(BaseSb baseSb, Map<String, Object> map, HttpServletRequest request) throws Exception {
        List<Map<String, String>> materialss = getMaterials(baseSb.getCaseRefGuid(), baseSb, request);

        //得到材料说明
        String clsm = getClsm(baseSb.getCaseRefGuid(), baseSb, request);

        String orgid = request.getParameter("orgid").toString();
        String caseName = request.getParameter("caseName").toString();

        String qj = request.getParameter("qj").toString();
        String sj = request.getParameter("sj").toString();

        SysOrgDept sysOrgDept = weixinQueryService.getSysOrgById(orgid);
        String caseDeptName=sysOrgDept.getOrgFullName();
        List<Map<String, String>> projectMailss = getYjxx(sysOrgDept, qj, sj, clsm, caseName);

        try {
            //事项所属警种
            String casePoliceCategory = String.valueOf(baseSb.getCasePoliceCategory() == null ? "" : baseSb.getCasePoliceCategory());
            if (org.apache.commons.lang.StringUtils.isBlank(casePoliceCategory)) {
                return false;
            }

            //事项编号
            String caseGuid = String.valueOf(baseSb.getCaseGuid() == null ? "" : baseSb.getCaseGuid());
            if (org.apache.commons.lang.StringUtils.isBlank(caseGuid)) {
                return false;
            }

            //事项代码
            String caseNo = String.valueOf(baseSb.getCaseNo() == null ? "" : baseSb.getCaseNo());
            if (org.apache.commons.lang.StringUtils.isBlank(caseNo)) {
                return false;
            }

            //部门编号
            String caseDeptID = String.valueOf(baseSb.getCaseDeptID() == null ? "" : baseSb.getCaseDeptID());
            if (org.apache.commons.lang.StringUtils.isBlank(caseDeptID)) {
                return false;
            }

            //部门名称
//            String caseDeptName = String.valueOf(baseSb.getCaseDeptName()==null?"":baseSb.getCaseDeptName());
//            if(org.apache.commons.lang.StringUtils.isBlank(caseDeptName)){
//                return false;
//            }

            //预约用户guid
            String userGuid = String.valueOf(baseSb.getUserGuid() == null ? "" : baseSb.getUserGuid());
            if (org.apache.commons.lang.StringUtils.isBlank(userGuid)) {
                return false;
            }

            JSONArray materials = JSONArray.parseArray(JSONArray.toJSONString(materialss));
            //材料附件信息
            if (null == materials) {
                materials = new JSONArray();
            }

            //基本信息
            ProjectItem projectItem = new ProjectItem();
            projectItem.setProjectCaseGuid(caseGuid);
            projectItem.setCaseNo(caseNo);
            projectItem.setCaseDeptCode(caseDeptID);
            projectItem.setCaseDeptName(caseDeptName);
            projectItem.setCreatorGuid(userGuid);
            projectItem.setPrjJzCode(casePoliceCategory);
            projectItem.setPrjCaseName(baseSb.getCaseName());

            projectItem.setRefGuid(baseSb.getCaseRefGuid());
            //办件邮寄信息
            JSONArray projectMails = JSONArray.parseArray(JSONArray.toJSONString(projectMailss));
            List<ProjectNetEms> mailList = new ArrayList<>();
            if (null != projectMails && 0 < projectMails.size()) {
                for (int i = 0; i < projectMails.size(); i++) {
                    JSONObject e = projectMails.getJSONObject(i);
                    ProjectNetEms projectNetEms = JSONObject.parseObject(e.toJSONString(), ProjectNetEms.class);
                    mailList.add(projectNetEms);
                }
                if (mailList.get(0).getType().equals(Constant.MAIL_TYEP_1) && mailList.get(0).getZffs().equals(Constant.MAIL_PAY_TYEP_0)) {
                    // EMS线下支付
                    projectItem.setIsMailMertal(Constant.MAIL_MERTAL_10);
                } else if (mailList.get(0).getType().equals(Constant.MAIL_TYEP_1) && mailList.get(0).getZffs().equals(Constant.MAIL_PAY_TYEP_1)) {
                    // EMS线上支付
                    projectItem.setIsMailMertal(Constant.MAIL_MERTAL_11);
                } else if (mailList.get(0).getType().equals(Constant.MAIL_TYPE_2) && mailList.get(0).getZffs().equals(Constant.MAIL_PAY_TYEP_0)) {
                    // 顺丰线下支付
                    projectItem.setIsMailMertal(Constant.MAIL_MERTAL_20);
                } else if (mailList.get(0).getType().equals(Constant.MAIL_TYPE_2) && mailList.get(0).getZffs().equals(Constant.MAIL_PAY_TYEP_1)) {
                    // 顺丰线上支付
                    projectItem.setIsMailMertal(Constant.MAIL_MERTAL_21);
                }
            } else {
                projectItem.setIsMailMertal(Constant.MAIL_MERTAL_0);
            }

            ProjectItem projectItem1 = weixinQueryService.doMattersApply(projectItem, materials, mailList);

            //开启工作流
            weixinQueryService.doWorkFlow(projectItem1);

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //得到材料
    private List<Map<String, String>> getMaterials(String caseGuid, BaseSb baseSb, HttpServletRequest request) {

        CaseLibrary caseView = weixinQueryService.loadMattersDetail(caseGuid);

        if (caseView != null) {
            List<CaseMaterial> caseMaterials = caseView.getMaterialList();
            baseSb.setCaseName(caseView.getCaseName());
            List<CasePay> casePays = caseView.getCasePay();
            baseSb.setCasePays(casePays);
            baseSb.setIsPay(caseView.getIsPay());
            List<Map<String, String>> materials = new ArrayList<>();
            caseMaterials.forEach(e -> {
                String caseMaterialId = e.getGuid();
                String isMust = e.getIsMust();
                String attId = request.getParameter("id_" + caseMaterialId);
                if (org.apache.commons.lang.StringUtils.isNotBlank(attId)) {
                    String size = request.getParameter("size_" + caseMaterialId);
                    String name = request.getParameter("name_" + caseMaterialId);
                    String[] attIds = attId.split("&&");
                    String[] sizes = size.split("&&");
                    String[] names = name.split("&&");
                    for (int i = 0; i < attIds.length; i++) {
                        Map<String, String> material = new HashMap<>();
                        material.put("materialGuid", caseMaterialId);
                        material.put("isHave", isMust);
                        material.put("friendlyFileName", names[i]);
                        material.put("contentSize", sizes[i]);
                        material.put("attGuid", attIds[i]);
                        materials.add(material);
                        material = null;
                    }
                }
            });

            return materials;
        } else {
            return null;
        }
    }

    //得到材料说明
    private String getClsm(String caseGuid, BaseSb baseSb, HttpServletRequest request) {
        CaseLibrary caseView = weixinQueryService.loadMattersDetail(caseGuid);

        if (caseView != null) {
            List<CaseMaterial> caseMaterials = caseView.getMaterialList();
            StringBuffer sb = new StringBuffer();
            caseMaterials.forEach(e -> {
                sb.append(e.getMaterial()).append(" ,");
            });

            if (sb.length() > 0) {
                sb.substring(0, sb.length() - 1);
            }

            return sb.toString();
        } else {
            return null;
        }
    }

    //得到邮寄信息
    private List<Map<String, String>> getYjxx(SysOrgDept sysOrgDept, String qjAddress, String sjAddress, String clsm, String caseName) {
        List<Map<String, String>> projectMails = new ArrayList<>();
        String orgName = sysOrgDept.getOrgName();
        String orgFullName = sysOrgDept.getOrgFullName();
        String orgPhone = sysOrgDept.getOrgPhone();

        if (!qjAddress.equals("")) {

            //上门取件的地址
            String[] qjAddresses = qjAddress.split("&&");

            //计算费用
            String zffy = "0";

            Map<String, String> qjMap = new HashMap<>();
            qjMap.put("sjrsf", "黑龙江省");
            qjMap.put("sjrcs", "大庆市");
            qjMap.put("sjrqx", orgFullName);
            qjMap.put("sjrjd", orgName);
            qjMap.put("sjryb", "163000");//大庆邮编
            qjMap.put("sjrxm", orgName);
            qjMap.put("sjrdh1", orgPhone);   //派出所电话
            qjMap.put("jjrsf", qjAddresses[0]);
            qjMap.put("jjrcs", qjAddresses[1]);
            qjMap.put("jjrqx", qjAddresses[2]);
            qjMap.put("jjrjd", qjAddresses[3]);
            qjMap.put("jjrxm", qjAddresses[4]);
            qjMap.put("jjrdh1", qjAddresses[5]);
            qjMap.put("jjryb", qjAddresses[6]);
            qjMap.put("bjmc", caseName);
            qjMap.put("bjsxcl", clsm);
            qjMap.put("source", "0");
            qjMap.put("type", "1");//1:EMS  2:顺丰
            qjMap.put("zffs", "0");//支付方式 1：在线支付  0：线下支付
            qjMap.put("zffy", zffy);//支付费用
            projectMails.add(qjMap);
        }

        if (!sjAddress.equals("")) {
            //送件地址
            String[] sjAddresses = sjAddress.split("&&");

            //计算费用
//            String pro = sjAddresses[0];
//            String city = sjAddresses[1];

            String zffy = "0";
/*            if(pro.equals("辽宁省") && city.equals("朝阳市")){//同省同市
                zffy = "0.01";//22
            }else if(pro.equals("辽宁省") && !city.equals("朝阳市")){//同省不同市
                zffy = "0.01";//22
            }else if(!pro.equals("辽宁省")){//不同省
                zffy = "0.01";//22
            }*/

            Map<String, String> sjMap = new HashMap<>();
            sjMap.put("sjrsf", sjAddresses[0]);
            sjMap.put("sjrcs", sjAddresses[1]);
            sjMap.put("sjrqx", sjAddresses[2]);
            sjMap.put("sjrjd", sjAddresses[3]);
            sjMap.put("sjrxm", sjAddresses[4]);
            sjMap.put("sjrdh1", sjAddresses[5]);
            sjMap.put("sjryb", sjAddresses[6]);
            sjMap.put("jjrsf", "黑龙江省");
            sjMap.put("jjrcs", "大庆市");
            sjMap.put("jjrqx", orgFullName);
            sjMap.put("jjrjd", orgName);
            sjMap.put("jjryb", "163000");
            sjMap.put("jjrxm", orgName);
            sjMap.put("jjrdh1", orgPhone);
            sjMap.put("bjmc", caseName);
            sjMap.put("bjsxcl", clsm);
            sjMap.put("source", "1");
            sjMap.put("type", "1");
            sjMap.put("zffs", "0");
            sjMap.put("zffy", zffy);
            projectMails.add(sjMap);
        }

        return projectMails;
    }


    /**
     * 办件材料上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "uploadPrj",method = POST)
    @ResponseBody
    public Object uploadAttachmentProject(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//        String id = request.getParameter("id").toString();
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("uploadform_" + id);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("uploadfile");
        StringBuffer sb = new StringBuffer();
        StringBuffer sbName = new StringBuffer();
        StringBuffer sbSize = new StringBuffer();
        if (files != null && files.size() > 0) {
            files.forEach(multipartFile -> {
                String fileName = multipartFile.getOriginalFilename();
                try {
                    InputStream inputStream = multipartFile.getInputStream();
                    File parentFile = new File(configInfo.getFileUpload());
                    if (!parentFile.exists()) {
                        parentFile.mkdirs();
                    }
                    File file = new File(parentFile, fileName);
                    long size = multipartFile.getSize();
                    if (size > 512000 && size < 1024000) {
                        Thumbnails.of(inputStream).scale(0.45f).toFile(file);
                    } else if (size > 1024000) {
                        Thumbnails.of(inputStream).scale(0.25f).toFile(file);
                    } else {
                        Thumbnails.of(inputStream).scale(1f).toFile(file);
                    }
                    size = file.length();

                    String guid = weixinQueryService.saveProjectAttchmentsAtt(FileUtils.File2byte(file));
                    FileInputStream input = new FileInputStream(file);
                    String time = weixinQueryService.getTime();
                    String yearAndMon = time.substring(0, 6);
                    String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
                    String ftpFileName = guid + "_" + yearAndMon + suffix;
                    FileUtils.uploadFile(configInfo.getFileServerHost(), Integer.parseInt(configInfo.getFileServerPort()), configInfo.getFileServerUsername(), configInfo.getFileServerPassword(), "", ftpFileName, input);
                    sb.append(guid).append("&&");
                    sbName.append(fileName).append("&&");
                    sbSize.append(size).append("&&");
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", sb.substring(0, sb.length() - 2).trim());
        map.put("name", sbName.substring(0, sbName.length() - 2).trim());
        map.put("size", sbSize.substring(0, sbSize.length() - 2).trim());
        return map;
    }

}
